package com.yunc.modules.oa.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrSpliter;
import com.yunc.common.utils.BaseConstant;
import com.yunc.modules.oa.entity.Leave;
import com.yunc.modules.oa.mapper.LeaveMapper;
import com.yunc.modules.oa.service.ILeaveService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户请假表 service实现
 *
 * @author concong tao
 * @since 2019-02-19
 */
@Service
public class LeaveServiceImpl extends ServiceImpl<LeaveMapper, Leave> implements ILeaveService {

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IdentityService identityService;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean saveLeave(Leave leave, Long userId) {
        leave.setUserId(userId);
        leave.setStatus(BaseConstant.OA_ACTIVITI_SUBMIT);
        leave.setCreateTime(DateUtil.date());
        // 计算时间
        long betweenHour = DateUtil.between(leave.getStartTime(), leave.getEndTime(), DateUnit.HOUR);
        long betweenDay = DateUtil.between(leave.getStartTime(), leave.getEndTime(), DateUnit.DAY);
        leave.setLeaveTime(String.valueOf(betweenHour));
        boolean flag = this.save(leave);
        if (!flag) {
            return flag;
        }
        Map<String,Object> map = new HashMap<>(1);
        map.put("staff", userId);
        map.put("day", betweenDay);
        // 流程启动
        Long id = leave.getId();
        // 先设置流程启动人
        identityService.setAuthenticatedUserId(String.valueOf(userId));
        ExecutionEntity executionEntity = (ExecutionEntity) runtimeService.startProcessInstanceByKey("leaveProcess", String.valueOf(id), map);
        List<Task> tasks = taskService.createTaskQuery().processInstanceId(executionEntity.getProcessInstanceId()).list();
        if (tasks != null && tasks.size() > 0) {
            Task task = tasks.get(0);
            // 需要下一个处理人
            String assignee = leave.getAssignee();
            if (assignee.contains(",")) {
                List<String> assigneeList = StrSpliter.split(assignee, ',', 0, true, true);
                taskService.setVariable(task.getId(), "assigneeList", assigneeList);
            } else {
                taskService.setVariable(task.getId(), "assignee", leave.getAssignee());
            }
            taskService.complete(task.getId());
        }
        return true;
    }
}
